import sys,os
from subprocess import run
from PySide6.QtCore import Qt, QFile, QIODevice, QTextStream, QDateTime, QDir, Slot
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QDialog
from Funcs.Config import Config

# 导入我们生成的界面
from Forms.LogWindow_UI import Ui_FormLog

class LogWindow(QDialog, Ui_FormLog):
    def __init__(self, parent = None):
        super().__init__()
        self.setupUi(self)
        self.__logPath = ""

        flags = self.windowFlags()
        self.setWindowFlags(flags & ~Qt.WindowContextHelpButtonHint)
    
    def AddOneLog(self, log):
        log_pure = log
        # if (log_pure.rfind("\r\n") >= 0):
        #     log_pure = log_pure[:-2]
        # elif (log_pure.rfind("\n") >= 0):
        #     log_pure = log_pure[:-1]
            
        if (len(log_pure) > 0):
            self.plainTextEdit.appendPlainText(log_pure)
            
        if (len(log) > 0):
            if (len(self.__logPath) > 0 and self.checkBox_SaveLog.isChecked()):
                file = QFile(self.__logPath)
                if not file.open(QIODevice.Text | QIODevice.Append):
                    return

                stream = QTextStream(file)
            
                stream << log
                stream.flush()
                file.close()
    
    def FindColor(self, log):
        colors_map = (("\033[0;30m", Qt.black), 
                      ("\033[0;31m", Qt.red), 
                      ("\033[0;32m", QColor.fromRgb(0, 170, 0)), #GREEN
                      ("\033[0;33m", QColor.fromRgb(255, 180, 0)), #YELLOW
                      ("\033[0;34m", Qt.blue), 
                      ("\033[0;35m", Qt.darkMagenta), 
                      ("\033[0;36m", Qt.darkCyan), 
                      ("\033[0m", Qt.black))
        
        i = 0xffffffff
        color = None
        for colors in colors_map:
            j = log.find(colors[0])
            if (j >= 0 and j < i):
                i = j
                color = colors
                
        return i, color

    def AddLog(self, log):
        log_str = log
        while len(log_str) > 0:
            i, color = self.FindColor(log_str)
            
            if (not color is None):
                log_part = log_str[:i]
                self.AddOneLog(log_part)

                log_str = log_str[i + len(color[0]):]
                tf = self.plainTextEdit.currentCharFormat()
                tf.setForeground(color[1])
                self.plainTextEdit.setCurrentCharFormat(tf)
            else:
                log_part = log_str
                self.AddOneLog(log_part)
                log_str = ""

    def SetDeviceIP(self, ip):
        self.setWindowTitle("设备日志" + (":" + ip if len(ip) > 0 else ""))
        self.__logPath = ""
        if len(ip) > 0:
            logPath = Config.GetCurrentPath() + "/Logs/" + "[" + ip + "]" + QDateTime.currentDateTime().toString("yyyyMMdd_HHmmss") + ".log"
            self.__logPath = logPath

            dir = QDir(Config.GetCurrentPath() + "/Logs/")
            if not dir.exists():
                dir.mkpath(dir.absolutePath())

        self.plainTextEdit.clear()
        self.label_LogPath.setText(self.__logPath)

    @Slot()
    def on_pushButton_OpenLog_clicked(self):
        if len(self.__logPath) > 0:
            os.startfile(self.__logPath)

    @Slot()
    def on_pushButton_OpenFolder_clicked(self):
        if len(self.__logPath) > 0:
            filePath = self.__logPath
            cmd = "explorer /select,\"%s\"" % filePath.replace('/', '\\')

            run(cmd, shell = True)
            
    @Slot()
    def on_pushButton_Clear_clicked(self):
        self.plainTextEdit.clear()
        
    @Slot()
    def on_label_LogPath_clicked(self):
        if len(self.__logPath) > 0:
            os.startfile(self.__logPath)
            
    @Slot()
    def on_closeButton_clicked(self):
        self.reject()



